package com.yao.yaooj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yao.yaooj.common.ErrorCode;
import com.yao.yaooj.constant.CommonConstant;
import com.yao.yaooj.exception.BusinessException;
import com.yao.yaooj.judge.JudgeService;
import com.yao.yaooj.model.dto.questionsubmit.QuestionSubmitAddRequest;
import com.yao.yaooj.model.dto.questionsubmit.QuestionSubmitQueryRequest;
import com.yao.yaooj.model.entity.*;
import com.yao.yaooj.model.entity.QuestionSubmit;
import com.yao.yaooj.model.enums.QuestionSubmitLanguageEnum;
import com.yao.yaooj.model.enums.QuestionSubmitStatusEnum;
import com.yao.yaooj.model.vo.QuestionSubmitVO;
import com.yao.yaooj.service.*;
import com.yao.yaooj.service.QuestionSubmitService;
import com.yao.yaooj.mapper.QuestionSubmitMapper;
import com.yao.yaooj.utils.SqlUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
* @author Lecoo
* @description 针对表【question_submit(题目提交)】的数据库操作Service实现
* @createDate 2025-04-20 15:56:57
*/
@Service
public class QuestionSubmitServiceImpl extends ServiceImpl<QuestionSubmitMapper, QuestionSubmit>
    implements QuestionSubmitService{

    @Resource
    private QuestionService questionService;

    @Resource
    private UserService userService;

    @Resource
    @Lazy
    //默认情况下，Spring 容器会在启动时预先实例化所有被 @Component 或其衍生注解（如 @Service, @Repository, @Controller 等）标记的 Bean。
    //如果某个 Bean 被标记为 @Lazy，则该 Bean 的实例化会被延迟到第一次实际使用时才进行。
    private JudgeService judgeService;

    /**
     * 提交题目
     *
     * @param questionSubmitAddRequest
     * @param loginUser
     * @return
     */
    @Override
    public long doQuestionSubmit(QuestionSubmitAddRequest questionSubmitAddRequest, User loginUser) {
        //todo 校验编程语言是否合法
        //先从用户的请求中拿到language
        String language = questionSubmitAddRequest.getLanguage();
        //根据枚举值把枚举值转成数据库中的值
        QuestionSubmitLanguageEnum languageEnum = QuestionSubmitLanguageEnum.getEnumByValue(language);
        if(languageEnum==null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"不支持的编程语言");
        }
        String value = languageEnum.getValue();
        // 判断实体是否存在，根据类别获取实体
        long questionId = questionSubmitAddRequest.getQuestionId();
        Question question = questionService.getById(questionId);
        if (question == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 是否已提交题目
        long userId = loginUser.getId();
        // 每个用户串行提交题目
        // 锁必须要包裹住事务方法
        //后面会优化的
//        QuestionSubmitService questionSubmitService = (QuestionSubmitService) AopContext.currentProxy();
//        synchronized (String.valueOf(userId).intern()) {
//            return questionSubmitService.doQuestionSubmitInner(userId, questionId);
//        }
        QuestionSubmit questionSubmit=new QuestionSubmit();
        questionSubmit.setUserId(userId);
        questionSubmit.setQuestionId(questionId);
        questionSubmit.setCode(questionSubmitAddRequest.getCode());
        questionSubmit.setLanguage(language);
        //设置初始状态
        questionSubmit.setStatus(QuestionSubmitStatusEnum.WAITING.getValue());
        questionSubmit.setJudgeInfo("{}");//判题信息
        boolean save=this.save(questionSubmit);
        if(!save){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"数据插入失败");
        }
        Long questionSubmitId=questionSubmit.getId();
        //  执行判题服务 异步的方式
        CompletableFuture.runAsync(()->{
            judgeService.doJudge(questionSubmitId);
        });
        return questionSubmitId;//获取到新纪录的ID
    }

    @Override
    public QueryWrapper<QuestionSubmit> getQueryWrapper(QuestionSubmitQueryRequest questionSubmitQueryRequest) {
        QueryWrapper<QuestionSubmit> queryWrapper = new QueryWrapper<>();
        if (questionSubmitQueryRequest == null) {
            return queryWrapper;
        }

        String language = questionSubmitQueryRequest.getLanguage();
        Integer status = questionSubmitQueryRequest.getStatus();
        Long questionId = questionSubmitQueryRequest.getQuestionId();
        Long userId = questionSubmitQueryRequest.getUserId();
        String sortField = questionSubmitQueryRequest.getSortField();
        long pageSize = questionSubmitQueryRequest.getPageSize();
        String sortOrder = questionSubmitQueryRequest.getSortOrder();

        // 拼接查询条件
        queryWrapper.eq(StringUtils.isNotBlank(language), "language", language);
        queryWrapper.eq(QuestionSubmitStatusEnum.getEnumByValue(status)!=null, "status", status);
        queryWrapper.eq(ObjectUtils.isNotEmpty(questionId), "questionId", questionId);
        queryWrapper.eq(ObjectUtils.isNotEmpty(userId), "userId", userId);
        queryWrapper.orderBy(SqlUtils.validSortField(sortField), sortOrder.equals(CommonConstant.SORT_ORDER_ASC),
                sortField);
        return queryWrapper;
    }


    @Override
    public QuestionSubmitVO getQuestionSubmitVO(QuestionSubmit questionSubmit, User loginUser) {
        QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
        //脱敏：仅本人或管理员可见提交信息
        long userId=loginUser.getId();//登录用户的ID
        if (userId != questionSubmit.getUserId() && !userService.isAdmin(loginUser)) {
            questionSubmitVO.setCode(null); //将不想返回的数据设置为空
        }

        return questionSubmitVO;
    }

    /**
     * 根据问题的分页，得到问题的封装类
     * 类似于for循环调用了getQuestionSubmitVO方法
     * @param questionSubmitPage
     * @param loginUser
     * @return
     */
    @Override
    public Page<QuestionSubmitVO> getQuestionSubmitVOPage(Page<QuestionSubmit> questionSubmitPage,User loginUser) {
        List<QuestionSubmit> questionSubmitList = questionSubmitPage.getRecords();
        //getRecords() 是 MyBatis-Plus 框架中分页对象（如 Page<T>）的一个方法，用于获取当前分页查询结果中的数据记录列表
        //getRecords() 方法返回的是当前分页查询结果中的数据部分，即满足查询条件的实体对象列表

        //创建新的分页对象，用于封装分页信息，包括当前页码、每页记录数、总记录数、总页数等
        Page<QuestionSubmitVO> questionSubmitVOPage = new Page<>(questionSubmitPage.getCurrent(), questionSubmitPage.getSize(), questionSubmitPage.getTotal());
        if (CollectionUtils.isEmpty(questionSubmitList)) {
            return questionSubmitVOPage;//返回空的分页对象
        }
//        // 1. 关联查询用户信息
//        //为什么要这么查数据？就想一次性查完，不用为了获得用户信息而多次去get请求该分页的信息，效率低，慢
//        Set<Long> userIdSet = questionSubmitList.stream()
//                .map(QuestionSubmit::getUserId)
//                .collect(Collectors.toSet());
//        //键为用户ID，值为对应的用户列表
//        Map<Long, List<User>> userIdUserListMap = userService.listByIds(userIdSet).stream()
//                //     List<User> users = [
//                //         User{id=1L, name="Alice", email="alice@example.com"},
//                //         User{id=2L, name="Bob", email="bob@example.com"},
//                //         User{id=3L, name="Charlie", email="charlie@example.com"}
//                //     ];
//                .collect(Collectors.groupingBy(User::getId));
//                //         Map<Long, List<User>> userIdUserListMap = {
//                //         1L: [User{id=1L, name="Alice", email="alice@example.com"}],
//                //         2L: [User{id=2L, name="Bob", email="bob@example.com"}],
//                //         3L: [User{id=3L, name="Charlie", email="charlie@example.com"}]
//                //     };
//        // 填充信息
//        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream()
//                .map(questionSubmit -> {
//            QuestionSubmitVO questionSubmitVO = QuestionSubmitVO.objToVo(questionSubmit);
//            Long userId = questionSubmit.getUserId();
//            User user = null;
//            if (userIdUserListMap.containsKey(userId)) {
//                user = userIdUserListMap.get(userId).get(0);
//            }
//            return questionSubmitVO;
//        }).collect(Collectors.toList());

        List<QuestionSubmitVO> questionSubmitVOList = questionSubmitList.stream()
                .map(questionSubmit -> {
            return getQuestionSubmitVO(questionSubmit, loginUser);
        }).collect(Collectors.toList());

        questionSubmitVOPage.setRecords(questionSubmitVOList);
        return questionSubmitVOPage;
    }
}




